#!/bin/bash
###
 # @FilePath: deploy.sh
 # @@author: wjj
 # @Date: 2025-08-04 19:14:10
 # @@Description: new js file
### 

# 部署脚本 - 包含前端构建和nginx配置更新 (不需要sudo权限)
set -e  # 遇到错误立即退出

echo "🚀 开始部署流程..."

# 步骤1: 彻底清理缓存和依赖
echo "🧹 彻底清理缓存..."
# npm cache clean --force
# rm -rf node_modules/.cache 2>/dev/null || true
# rm -rf dist 2>/dev/null || true

echo "📦 重新安装依赖..."
pnpm install --no-frozen-lockfile

# 步骤2: 构建项目
echo "🔨 构建前端项目..."
npm run build

# 验证构建结果
echo "🔍 验证构建结果..."
if [ -d "dist" ]; then
    echo "   ✅ dist目录已生成"
    echo "   📁 构建文件列表："
    ls -la dist/js/ 2>/dev/null | head -5 || echo "   ⚠️  js目录不存在"
    ls -la dist/css/ 2>/dev/null | head -5 || echo "   ⚠️  css目录不存在"
else
    echo "   ❌ dist目录生成失败！"
    exit 1
fi

# 步骤3: 验证nginx配置语法
# echo "🔍 验证nginx配置语法..."
# if nginx -t 2>/dev/null; then
#     echo "   ✅ nginx配置语法正确"
# else
#     echo "   ❌ nginx配置语法错误，请检查 fastbot.conf"
#     echo "   可以运行: nginx -t 查看详细错误信息"
#     exit 1
# fi

# # 步骤4: 重新加载nginx配置
# echo "🔄 重新加载nginx配置..."
# if nginx -s reload 2>/dev/null; then
#     echo "   ✅ nginx配置重新加载成功"
# else
#     echo "   ❌ nginx重新加载失败，可能需要手动重启nginx"
#     echo "   请手动执行: sudo nginx -s reload"
# fi

# # 步骤5: 清理潜在的nginx缓存
# echo "🧹 清理nginx缓存（如果有）..."
# # 一些常见的nginx缓存目录
# CACHE_DIRS="/tmp/nginx /var/cache/nginx /usr/local/var/cache/nginx"
# for dir in $CACHE_DIRS; do
#     if [ -d "$dir" ]; then
#         echo "   🗑️  清理缓存目录: $dir"
#         rm -rf "$dir"/* 2>/dev/null || true
#     fi
# done

# # 步骤5: 验证部署
# echo "🔍 验证部署状态..."
# echo "   - 检查dist目录: $(ls -la dist/ | head -5)"
# echo "   - 检查config.ini: $(test -f dist/config.ini && echo '✅ 存在' || echo '❌ 缺失')"
# echo "   - nginx配置路径: $(pwd)/fastbot.conf"

echo ""
echo "🎉 部署完成！"
echo "📋 部署摘要:"
echo "   - npm依赖: 已重新安装"
echo "   - 前端构建: 已完成 $(date '+%Y-%m-%d %H:%M:%S')"
echo "   - nginx配置: 已验证并重载"
echo "   - nginx缓存: 已清理"
echo "   - 配置文件: $(test -f dist/config.ini && echo '已就绪' || echo '需要检查')"
echo ""
echo "🌐 访问地址: http://192.168.32.21:8888"

echo ""
echo "🚨 重要: 如果页面仍显示旧版本，请按以下步骤清理缓存:"
echo "   1️⃣  浏览器强刷: Ctrl+F5 (Windows) 或 Cmd+Shift+R (Mac)"
echo "   2️⃣  清除浏览器缓存: F12 → Network → 勾选 'Disable cache'"
echo "   3️⃣  隐私模式测试: 打开隐私/无痕浏览窗口访问"
echo "   4️⃣  如仍有问题，等待5-10分钟让CDN缓存过期"

echo ""
echo "🔧 调试命令:"
echo "   - 检查nginx日志: tail -f /usr/local/var/log/nginx/fastbot.error.log"
echo "   - 手动重启nginx: sudo nginx -s reload"
echo "   - 验证文件时间戳: ls -la dist/"
echo "   - 检查文件hash: ls -la dist/js/ dist/css/"

# 提示nginx配置信息
echo ""
echo "💡 nginx配置:"
echo "   - 配置文件位置: $(pwd)/fastbot.conf"
echo "   - 确保nginx主配置包含: include $(pwd)/fastbot.conf;"
echo "   - HTML文件: 不缓存"
echo "   - JS/CSS文件: 智能缓存（有hash=长期，无hash=短期）" 